
#import "WXSBooksViewController.h"
#import "WXSBooksTableViewCell.h"
#import "WXSBooksHeaderView.h"
#import "WXSBooksFooterView.h"
#import "WXSMainDetailViewController.h"

static NSString * const identifier = @"cell";

@interface WXSBooksViewController ()<UITableViewDelegate, UITableViewDataSource,WXSBooksTableViewCellDelegate,UIGestureRecognizerDelegate,CAAnimationDelegate>

@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSMutableArray * dataArray;//数据源
@property (nonatomic, strong) WXSBooksHeaderView * headerView;//头部视图
@property (nonatomic, strong) WXSBooksFooterView * footerView;//底部视图
@property (nonatomic, assign) BOOL isSelected;//是否点击button

@property(nonatomic,strong)UIButton *cancelButton;
@property(nonatomic,strong)UIButton *checkButton;
@property (nonatomic, strong) NSIndexPath * currentIndexPath;

- (void)_initializeAppearance;//初始化

@end

@implementation WXSBooksViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _isSelected = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self _initializeAppearance];
    
}


#pragma mark - private method

- (void)_initializeAppearance
{
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = self.footerView;
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WXSBooksTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    NSInteger number = [self.dataArray[indexPath.row] integerValue];
    if (number >= 60)
    {
        cell.leftLabel.hidden = YES;
        cell.rightLabel.hidden = NO;
        cell.rightLabel.text = [NSString stringWithFormat:@"今日睡眠质量%d", number];
    }
    else
    {
        cell.leftLabel.hidden = NO;
        cell.rightLabel.hidden = YES;
        cell.leftLabel.text = [NSString stringWithFormat:@"今日睡眠质量%d", number];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - WXSBooksTableViewCellDelegate

-(void)sleepBookCellDidPressMidButton:(WXSBooksTableViewCell *)cell
{
    
    if (_isSelected)
    {
        [self addAnimationOnButtonWithCell:cell];
        _currentIndexPath = [self.tableView indexPathForCell:cell];
    }
    else
    {
        [self removeAnimationOnButtonWithCell:cell];
    }
    _isSelected = !_isSelected;
}

- (void)addAnimationOnButtonWithCell:(WXSBooksTableViewCell *)cell
{
    
    cell.middleButton.userInteractionEnabled = NO;
    cell.checkButton.hidden = NO;
    cell.cancelButton.hidden = NO;
    CABasicAnimation *basicAnimation = [CABasicAnimation animation];
    basicAnimation.keyPath = @"position";
    basicAnimation.duration = 0.3;
    basicAnimation.delegate = self;
    basicAnimation.fromValue = [NSValue valueWithCGPoint:CGPointMake(CGRectGetWidth(cell.bounds) / 2, CGRectGetHeight(cell.bounds) / 2)];
    [cell.cancelButton.layer addAnimation:basicAnimation forKey:nil];
    [cell.checkButton.layer addAnimation:basicAnimation forKey:nil];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(basicAnimation.duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        cell.middleButton.userInteractionEnabled = YES;
    });
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    [tap setNumberOfTapsRequired:1];
    tap.cancelsTouchesInView = NO;
    tap.delegate = self;
    [self.tableView addGestureRecognizer:tap];
}

- (void)tap:(UITapGestureRecognizer *)tap
{
    if (tap.state == UIGestureRecognizerStateEnded)
    {
        WXSBooksTableViewCell *cell = [self.tableView cellForRowAtIndexPath:_currentIndexPath];
        CGPoint point = [tap locationInView:self.tableView];
        if (![cell.cancelButton pointInside:point withEvent:nil] && ![cell.checkButton pointInside:point withEvent:nil])
        {
            [self removeAnimationOnButtonWithCell:cell];
            [self.tableView removeGestureRecognizer:tap];
            _isSelected = YES;
        }
    }
}

- (void)removeAnimationOnButtonWithCell:(WXSBooksTableViewCell *)cell
{
    cell.middleButton.userInteractionEnabled = NO;
    CABasicAnimation *basicAnimation = [CABasicAnimation animation];
    basicAnimation.keyPath = @"position";
    basicAnimation.duration = 0.3;
    basicAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(CGRectGetWidth(cell.bounds) / 2, CGRectGetHeight(cell.bounds) / 2)];
    basicAnimation.delegate = self;
    basicAnimation.fillMode = kCAFillModeForwards;
    basicAnimation.removedOnCompletion = false;
    [cell.cancelButton.layer addAnimation:basicAnimation forKey:nil];
    [cell.checkButton.layer addAnimation:basicAnimation forKey:nil];
    self.checkButton = cell.checkButton;
    self.cancelButton = cell.cancelButton;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(basicAnimation.duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        cell.middleButton.userInteractionEnabled = YES;
    });
}

- (void)sleepBookCellDidPressCancelButton:(UIButton *)sender
{
    NSLog(@"1");
}

- (void)sleepBookCellDidPressCheckButton:(UIButton *)sender
{
    WXSMainDetailViewController *vc = [[WXSMainDetailViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch;
{
    id touchView = [touch view];
    if ([touchView isKindOfClass:[UIButton class]]) {
        return NO;
    }
    return YES;
}

#pragma mark - Animation Delegate

- (void)animationDidStart:(CAAnimation *)anim
{
    if (!_isSelected)
    {
        self.checkButton.hidden = NO;
        self.cancelButton.hidden = NO;
    }
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if (_isSelected)
    {
        self.checkButton.hidden = YES;
        self.cancelButton.hidden = YES;
    }
    
}

#pragma mark - action



#pragma mark - lazy load

- (UITableView *)tableView
{
    if (_tableView == nil)
    {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64 - 49) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [_tableView registerNib:[UINib nibWithNibName:@"WXSBooksTableViewCell" bundle:nil] forCellReuseIdentifier:identifier];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil)
    {
        _dataArray = [NSMutableArray arrayWithCapacity:0];
        for (int i = 0; i < 50; i ++)
        {
            NSString *str = [NSString stringWithFormat:@"%d", arc4random() % 100];
            [_dataArray addObject:str];
        }
    }
    return _dataArray;
}

- (WXSBooksHeaderView *)headerView
{
    if (_headerView == nil)
    {
        _headerView = [[[NSBundle mainBundle] loadNibNamed:@"WXSBooksHeaderView" owner:nil options:nil] firstObject];
        _headerView.goodSleepLabel.layer.cornerRadius = 3;
        _headerView.goodSleepLabel.layer.borderWidth = 1;
        _headerView.goodSleepLabel.layer.borderColor = [UIColor colorWithRed:0.344 green:0.482 blue:1.000 alpha:1.000].CGColor;
        _headerView.badSleepLabel.layer.cornerRadius = 3;
        _headerView.badSleepLabel.layer.borderWidth = 1;
        _headerView.badSleepLabel.layer.borderColor = [UIColor colorWithRed:0.344 green:0.482 blue:1.000 alpha:1.000].CGColor;
    }
    return _headerView;
}

- (WXSBooksFooterView *)footerView
{
    if (_footerView == nil)
    {
        _footerView = [[[NSBundle mainBundle] loadNibNamed:@"WXSBooksFooterView" owner:nil options:nil] firstObject];
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yy年MM月dd日HH时mm分"];
        _footerView.startTimeLabel.text = [formatter stringFromDate:date];
    }
    return _footerView;
}

@end
